package it.unisannio.lesim.fsm;

import java.util.ArrayList;

/**
 *
 * @author Marco Calisti
 * @author Antonio Cuomo
 * @author Rocco Mazzeo
 * @author Francesco Pacilio
 * 
 */

public class State {
      
    private boolean isFinal = false, isError=false;
    private String name, description;
    private ArrayList transitions;
    
    public State(String name, String description){
        this.description=description;
        this.name=name;
        this.transitions = new ArrayList();
    }
        
    public ArrayList getTransitions() {
        return transitions;
    }

    public boolean isIsError() {
        return isError;
    }

    public void setIsError(boolean isError) {
        this.isError = isError;
    }

    public boolean isIsFinal() {
        return isFinal;
    }

    public void setIsFinal(boolean isFinal) {
        this.isFinal = isFinal;
    }
    
    public String getName(){
        return name;
    }
    
    public String getDescription(){
        return description;
    }
            
    public String receiveMessage(Message m, Message lastMessage) {
        //bisogna aggiustare il get time, per far in modo che cacola il tutto in millisecondi
        long time = ((m.getSec()*1000)+(m.getUsec()/1000))-((lastMessage.getSec()*1000)+(lastMessage.getUsec()/1000));
        long messageTime= (m.getSec()*1000)+(m.getUsec()/1000);
        String typeMessage = m.getType();
        Transition t = null;
        for(int i=0; i<transitions.size(); i++){
           t = (Transition)transitions.get(i);
           if(t.check(time, typeMessage, m.getFields(), messageTime)){
               return t.getNextState();
           }
        }
        
        return name;
    }
    
    public void addTransition(FSM fsm, String nextState, String cond, String action){
        transitions.add(new Transition(fsm, nextState, cond, action));
    }
    
}
